<template>
  <div class="app-container purchasewarehouseorder">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-date-picker
        v-model="listQuery.startTime"
        class="filter-item"
        default-time="00:00:00"
        value-format="timestamp"
        placeholder="选择开始日期"
        style="width: 140px"
        type="datetime"
      />
      -
      <el-date-picker
        v-model="listQuery.endTime"
        class="filter-item"
        default-time="23:59:59"
        value-format="timestamp"
        placeholder="选择结束日期"
        style="width: 140px"
        type="datetime"
      />
      <el-select
        v-model="listQuery.storeId"
        clearable
        style="width: 200px"
        class="filter-item"
        placeholder="请选择门店" >
        <el-option v-for="(item,index) in storeList" :key="index" :label="item.storeName" :value="item.id" />
      </el-select>
      <el-input
        v-model="listQuery.sendOrderNo"
        class="filter-item"
        clearable
        placeholder="输入单号"
        style="width: 140px;"
      />
      <el-input
        v-model="listQuery.skuSearch"
        clearable
        class="filter-item"
        style="width: 160px;"
        placeholder="输入条码/商品名称"
      />
      <el-select v-model="listQuery.sendOrderState" class="filter-item" clearable placeholder="请选择状态" style="width: 120px" >
        <el-option v-for="(item,index) in statusMap" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button
        class="filter-item"
        icon="el-icon-search"
        type="primary"
        @click="handleFilter"
      >查找</el-button>
      <el-button
        v-permission="['warehouse:salessendorder:create']"
        class="filter-item"
        icon="el-icon-edit"
        type="primary"
        @click="handleCreate"
      >添加</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-data-analysis"
        @click="skuSummary"
      >导出</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-data-analysis"
        @click="handleImport"
      >导入</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      element-loading-text="正在查询中。。。"
      fit
      highlight-current-row
      size="small"
      style="white-space: pre-line"
    >
      <el-table-column align="center" label="单号" prop="sendOrderNo" width="150px">
        <template slot-scope="scope">
          <el-link :underline="false" type="primary" @click="handleDetail(scope.row)">{{ scope.row.sendOrderNo }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="出库时间" prop="sendOutTime">
        <template slot-scope="scope">{{ scope.row.sendOutTime | formatGmt }}</template>
      </el-table-column>
      <el-table-column align="center" label="出库数量" prop="sendOrderGoodsCount"/>
      <el-table-column align="center" label="出库金额" prop="sendOrderGoodsPrice">
        <template slot-scope="scope">{{ scope.row.sendOrderGoodsPrice / 100 }}</template>
      </el-table-column>
      <el-table-column align="center" label="门店" prop="storeName"/>
      <el-table-column align="center" label="操作人" prop="adminRealname"/>
      <el-table-column align="center" label="确认人" prop="sendOrderConfirmRealname"/>
      <el-table-column align="center" label="状态" prop="sendOrderState" >
        <template slot-scope="scope">
          <el-tag v-if=" scope.row.sendOrderState === 0">待出库</el-tag>
          <el-tag v-if=" scope.row.sendOrderState === 1">已出库</el-tag>
          <el-tag v-if=" scope.row.sendOrderState === 2" type="danger">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="300" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-permission="['warehouse:salessendorder:audit']"
            v-if="scope.row.sendOrderState =='0'"
            size="mini"
            type="primary"
            @click="handleAudit(scope.row)"
          >审批</el-button>
          <el-button
            v-permission="['warehouse:salessendorder:update']"
            v-if="scope.row.sendOrderState!='1'"
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            v-permission="['warehouse:salessendorder:detail']"
            size="mini"
            type="primary"
            @click="handleDetail(scope.row)"
          >查看</el-button>
          <el-button
            v-permission="['warehouse:purchasewarehouseorder:detail']"
            type="primary"
            size="mini"
            @click="handlePrint(scope.row)"
          >打印</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="listQuery.limit"
      :page.sync="listQuery.pageNo"
      :total="total"
      @pagination="getList"
    />
    <!-- 审核对话框 -->
    <el-dialog
      v-loading="auditFormLoading"
      :visible.sync="auditDialogVisible"
      center
      width="30%">
      <el-form ref="auditDataForm" :model="auditDataForm">
        <el-form-item align="center">
          <el-radio-group v-model="auditDataForm.sendOrderState" >
            <el-radio label="1" @change="changeSendOrderState">通过</el-radio>
            <el-radio label="2" @change="changeSendOrderState">驳回</el-radio>
          </el-radio-group>
        </el-form-item >
        <el-form-item v-if="auditDataForm.sendOrderState == '2'" label="驳回理由">
          <el-input v-model="auditDataForm.auditComment" placeholder="" rows="3" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="auditOrder()">确认</el-button>
        <el-button v-if="auditDataForm.sendOrderState == '1'" type="primary" @click="auditOrderAndEntryStore()">一键入库门店</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog v-loading="optloading" :width="optDiaLogWidth" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="left"
        label-width="100px"
        status-icon
      >
        <el-form-item prop="warehouseId">
          <label slot="label">仓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库</label>
          <el-select v-model="dataForm.warehouseId" placeholder="请选择" @change="ifCanSelSpu">
            <el-option v-for="(key, index) in warehouseList" :key="index" :label="key.warehouseName" :value="key.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="单据备注" prop="sendOrderInfo">
          <el-col :span="12">
            <el-input v-model="dataForm.sendOrderInfo" clearable placeholder="" type="textarea"/>
          </el-col>
        </el-form-item>
        <el-form-item prop="storeId">
          <label slot="label">门&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;店</label>
          <el-select v-model="dataForm.storeId" placeholder="请选择">
            <el-option v-for="(key, index) in storeList" :key="index" :label="key.storeName" :value="key.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库商品">
          <el-col :span="4"><span>已选择({{ selectSpuList.length>0?selectSpuList.length :'0' }})件商品</span></el-col>
          <el-col :span="10">
            <el-button :disabled="dataForm.warehouseIsSelected" size="mini" type="primary" @click="handleSpuAdd(dataForm.warehouseId)" >选择商品</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="商品详情" prop="salesSendOrderGoodsDTOS">
          <el-table
            :data="selectSpuList"
            border
            fit
            highlight-current-row
            size="small"
            style="white-space: pre-line">
            <el-table-column v-if="hidden" prop="goodsId" align="center" label="goodsId"/>
            <el-table-column v-if="hidden" prop="spuName"/>
            <el-table-column v-if="hidden" prop="skuName"/>
            <el-table-column v-if="hidden" prop="skuId"/>
            <el-table-column v-if="hidden" prop="spuId"/>
            <el-table-column align="center" label="商品" prop="goodsName" width="180px">
              <template slot-scope="scope">
                <el-col :span="6"><img :src="scope.row.img + '?x-oss-process=style/100px'" width="40" ></el-col>
                <el-col :span="18" style="padding-top: 15px;">{{ scope.row.goodsName }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="条形码" prop="barCode" />
            <el-table-column align="center" label="单位" prop="unit" width="50px"/>
            <el-table-column align="center" label="平均成本" width="70px">
              <template slot-scope="scope">
                <el-col>{{ (scope.row.averPrice / 100).toFixed(2) }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="可用库存" prop="warehouseSkuNum" width="80px"/>
            <el-table-column align="center" label="出库数量" prop="sendGoodsStock" width="120px">
              <template slot-scope="scope">
                <el-form ref="scope.row" :rules="spuNumFormRules" status-icon >
                  <el-form-item>
                    <el-input v-model="scope.row.sendGoodsStock" placeholder=""/>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="出库金额" width="100px">
              <template slot-scope="scope">
                <el-form ref="scope.row" :rules="spuPriceFormRules">
                  <el-form-item prop="spuPrice">
                    <el-input v-model="scope.row.sendGoodsAllPrice" placeholder=""/>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="出库单价" width="100px">
              <template slot-scope="scope">
                <el-col v-if="scope.row.sendGoodsAllPrice && scope.row.sendGoodsStock"><span>{{ (scope.row.sendGoodsAllPrice / scope.row.sendGoodsStock).toFixed(2) }}</span></el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="60px">
              <template slot-scope="scope">
                <el-link :underline="false" @click="removeSpu(scope.row.skuId)"><span style="color: red;">移除</span></el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="出库时间" prop="sendOutTime">
          <el-col :span="6">
            <el-date-picker
              v-model="dataForm.sendOutTime"
              class="filter-item"
              default-time="00:00:00"
              placeholder="选择出库时间"
              type="datetime"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="出库总额" prop="totalPrice">
          <span>{{ selSpuListTotalPrice }}</span>
        </el-form-item>
        <el-form-item label="出库总数" prop="total">
          <span>{{ selSpuListTotal }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData(0)">确认出库</el-button>
        <el-button v-else type="primary" @click="updateData(0)">确认出库</el-button>
      </div>
    </el-dialog>
    <!-- 添加商品 -->
    <el-dialog
      :visible.sync="spuDialogFormVisible"
      :width="spuDialogFormWidth"
      :custom-class="spuDialogClass"
      title="商品选择">
      <template>
        <div class="app-container" style="padding-bottom: 0;padding-top: 0;">
          <!-- 查询和其他操作 -->
          <div class="filter-container">
            <el-cascader :options="categoryOptions" :props="{ checkStrictly: true }" class="filter-item" clearable filterable placeholder="请选择类目" style="width: 200px;" @change="handleCategoryOption" />
            <el-input
              v-model="listSpuQuery.search"
              class="filter-item"
              clearable
              placeholder="输入名称或条码"
              style="width: 200px;"
            />
            <el-button
              class="filter-item"
              icon="el-icon-search"
              type="primary"
              @click="handleSpuFilter"
            >查找</el-button>
          </div>

          <!-- 查询结果 -->
          <el-table
            v-loading="listSpuLoading"
            ref="spuTable"
            :data="spuList"
            :row-key="getRowKey"
            border
            element-loading-text="正在查询中。。。"
            fit
            highlight-current-row
            max-height="400"
            size="small"
            style="white-space: pre-line"
            @selection-change="selectChange"
          >
            <el-table-column
              :reserve-selection="true"
              :selectable="ifCanSelectSpu"
              align="center"
              type="selection"
              width="55" />
            <el-table-column v-if="hidden" align="center" label="goodsId" prop="goodsId"/>
            <el-table-column align="center" label="商品名称" prop="goodsName" width="180px">
              <template slot-scope="scope">
                <el-col :span="6"><img :src="scope.row.img + '?x-oss-process=style/100px'" width="40" ></el-col>
                <el-col :span="18" style="padding-top: 15px;">{{ scope.row.goodsName }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" prop="unit"/>
            <el-table-column align="center" label="条形码" prop="barCode"/>
            <el-table-column align="center" label="平均成本">
              <template slot-scope="scope">
                <el-col>{{ (scope.row.averPrice / 100).toFixed(2) }}</el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="可用库存" prop="warehouseSkuNum"/>
          </el-table>
          <pagination
            v-show="spuListTotal>0"
            :limit.sync="listSpuQuery.limit"
            :page.sync="listSpuQuery.pageNo"
            :total="spuListTotal"
            :pager-count="5"
            layout="prev, pager, next"
            style="padding-bottom: 0;padding-top: 0;"
            @pagination="listGoods"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="spuDialogFormVisible=false">取消</el-button>
          <el-button type="primary" @click="saveWarehouseSpu">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入弹窗 -->
    <el-dialog
      :visible.sync="importDialogVisible"
      title="导入出库单"
      width="35%"
    >
      <el-table
        v-loading="resultListLoad"
        :data="resultList"
        border
        element-loading-text="正在查询中。。。"
        fit
        highlight-current-row
        size="small"
        style="white-space: pre-line"
      >
        <el-table-column align="center" label="导入结果">
          <template slot-scope="scope">
            <el-col>{{ scope.row }}</el-col>
          </template>
        </el-table-column>
      </el-table>
      <div style="border:none;">
        <el-button icon="el-icon-document-copy" type="primary" size="small" style="margin-left: 15px;" @click="checkFile">选择文件</el-button>
        <span>{{ fileName }}</span>
        <el-input id="fileinput" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" style="display: none;" @change="checkFileSure"/>
        <el-link type="primary" href="../../static/excel/salesSendTemplate.xls" target="_blank" download="出库单模板.xls">下载模板</el-link>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button :disabled="(!fileName)" :loading="importOptLoading" type="primary" @click="salesSendImportExcel">导 入</el-button>
        <el-button type="primary" @click="closeImportExcel">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 打印 -->
    <el-dialog :visible.sync="dialogTableVisible" title="打印" class="printBox">
      <printHtml :outbound="2" :p-order-id="pOrderId" />
    </el-dialog>
  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.el-form-item__label {
  padding-right: 0!important;
}

.el-form :not(.is-required) > .el-form-item__label{
  padding-left: 10px;
}
.spuDialogClass .el-dialog__body{
  padding-bottom: 0;
  padding-top: 10px;
}
  .spuDialogClass .el-dialog__footer{
    padding-top: 0;
  }
</style>

<script>
import { active, audit, auditAndStoreEntry, create, del, list, update, importExcel } from '@/api/salessendorder'
import { formatDateAndTime } from '@/filters'
import { goodsPriceLimit, goodsNumLimit } from '@/utils/validate'
import { listWareHousesByPara, exportSkuSummary } from '@/api/warehouse'
import { timestampToTime } from '@/utils/dateTimeUtil'
import { listStoresByPara } from '@/api/store'
import { listWarehouseSkusByPara, querySkusByWarehouseId } from '@/api/salessendordergoods'
import { categorySecondLevelTree, categoryTree } from '@/api/category'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const extraStatusMap = {
  '0': '待出库',
  '1': '已出库',
  '2': '驳回'
}
export default {
  name: 'SalesSendOrder',
  components: { Pagination },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return ''
      }
      return formatDateAndTime(time)
    },
    formatOrderState(state) {
      switch (state) {
        case 0 : return '待出库'
        case 1 : return '已出库'
        case 2 :
          return '驳回'
        default : return ''
      }
    }
  },
  data() {
    return {
      dialogTableVisible: false,
      pOrderId: '', // 844
      extraStatusMap,
      statusMap: [{ value: 0, name: '待出库' }, { value: 1, name: '已出库' }, { value: 2, name: '驳回' }],
      list: undefined,
      optloading: false,
      warehouseList: [],
      storeList: [],
      spuList: [],
      selectSpuList: [],
      selectGoodList: [],
      categoryOptions: [],
      resultList: [],
      resultListLoad: false,
      spuListTotal: 0,
      importOptLoading: false,
      total: 0,
      listLoading: true,
      listSpuLoading: true,
      auditFormLoading: false,
      salesSendImportDialogVisible: false,
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtCreate: undefined,
        sendOrderNo: undefined,
        sendOrderState: undefined,
        skuSearch: undefined
      },
      hidden: false,
      fileName: '',
      listSpuQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtCreate: undefined,
        sendOrderNo: undefined,
        warehouseId: undefined,
        search: '',
        categoryIds: '',
        categorySecondIds: '',
        saleSendOrderId: undefined
      },
      options: [],
      categoryList: [],
      categorySecondList: [],
      dataForm: {
        id: undefined,
        salesSendOrderGoodsDTOS: [],
        sendOrderState: 0,
        totalPrice: 0,
        total: 0,
        warehouseId: undefined,
        warehouseIsSelected: true,
        sendOrderConpon: 0,
        storeInfo: {},
        storeName: undefined,
        storeId: undefined
      },
      auditDataForm: {
        auditComment: '',
        sendOrderState: '0',
        salesSendOrderId: undefined,
        storePurchaseOrderId: undefined,
        storeStockEntryId: undefined
      },
      commentShow: false,
      dialogFormVisible: false,
      dialogStatus: '',
      auditDialogVisible: false,
      spuDialogFormVisible: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      spuDialogFormWidth: '60%',
      spuNumFormRules: {
        spuNum: [

        ]
      },
      spuPriceFormRules: {
        spuPrice: [

        ]
      },
      rules: {
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        storeId: [
          { required: true, message: '请选择门店', trigger: 'blur' }
        ],
        sendOutTime: [
          { required: true, message: '请选择出库时间', trigger: 'blur' }
        ]
      },
      optDiaLogWidth: '80%',
      spuDialogClass: 'spuDialogClass',
      goodNumFormatValid: true,
      goodNumMaxValid: true,
      goodPriceValid: true,
      importDialogVisible: false
    }
  },
  computed: {
    selSpuListTotal: function() {
      if (this.selectSpuList.length) {
        let total = 0
        for (let i = 0; i < this.selectSpuList.length; i++) {
          if (this.selectSpuList[i].sendGoodsStock && goodsNumLimit(this.selectSpuList[i].sendGoodsStock)) {
            total += parseFloat(this.selectSpuList[i].sendGoodsStock)
          }
        }
        return total.toFixed(3)
      }
    },
    selSpuListTotalPrice: function() {
      let totalPrice = 0
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (this.selectSpuList[i].sendGoodsAllPrice && this.selectSpuList[i].sendGoodsStock) {
          totalPrice += parseFloat(this.selectSpuList[i].sendGoodsAllPrice)
        }
      }
      return totalPrice.toFixed(2)
    }
  },
  created() {
    this.getList()
    this.listStoresByPara()
  },

  methods: {
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      if (this.listQuery.startTime && this.listQuery.startTime !== '') {
        var startTimeLong = this.listQuery.startTime
        this.listQuery.insertStartTime = timestampToTime(startTimeLong)
      }
      if (this.listQuery.endTime && this.listQuery.endTime !== '') {
        var endTimeLong = this.listQuery.endTime
        this.listQuery.insertEndTime = timestampToTime(endTimeLong)
      }
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSpuFilter() {
      this.listSpuQuery.pageNo = 1
      this.listGoods()
    },
    resetForm() {
      this.selectSpuList = []
      this.spuListTotal = 0
      this.storeList = []
      this.dataForm = {
        id: undefined,
        salesSendOrderGoodsDTOS: [],
        totalPrice: 0.0,
        total: 0,
        sendOrderConpon: 0,
        warehouseId: undefined,
        warehouseIsSelected: true,
        storeInfo: undefined,
        storeId: undefined
      }
      this.listSpuQuery = {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtCreate: undefined,
        sendOrderNo: undefined,
        warehouseId: undefined,
        search: '',
        categoryIds: '',
        categorySecondIds: '',
        warehouseOrderId: undefined
      }
    },
    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 0 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    listWareHousesByPara() {
      // listWareHousesByPara({ status: 1, isMain: 1 })
      listWareHousesByPara({ status: 1 })
        .then(response => {
          this.warehouseList = response.data.data
        })
        .catch(() => {
          this.warehouseList = []
        })
    },
    listStoresByPara() {
      this.listQuery.status = 1
      listStoresByPara(this.listQuery)
        .then(response => {
          this.storeList = response.data.data
        })
        .catch(() => {
          this.storeList = []
        })
    },
    handleCreate() {
      this.resetForm()
      this.listWareHousesByPara()
      this.listStoresByPara()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.goodNumFormatValid = true
      this.goodNumMaxValid = true
      this.goodPriceValid = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(status) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          let isHasEmpValue = ''
          let goodNumFormatValid = true
          let goodNumValue = ''
          let goodNumMaxValid = true
          let goodNumvalueMax = ''
          let goodPriceValid = true
          let goodValuePrice = ''
          for (let i = 0; i < selectSpuList.length; i++) {
            if (!selectSpuList[i].sendGoodsStock || !selectSpuList[i].sendGoodsAllPrice) {
              isHasEmptyValue = true
              isHasEmpValue = selectSpuList[i].spuName
              break
            }
            if (!goodsNumLimit(selectSpuList[i].sendGoodsStock)) {
              goodNumFormatValid = false
              goodNumValue = selectSpuList[i].spuName
              break
            }
            if (selectSpuList[i].sendGoodsStock && selectSpuList[i].warehouseSkuNum && selectSpuList[i].sendGoodsStock > selectSpuList[i].warehouseSkuNum) {
              goodNumMaxValid = false
              goodNumvalueMax = selectSpuList[i].spuName
              break
            }
            if (!goodsPriceLimit(selectSpuList[i].sendGoodsAllPrice)) {
              goodPriceValid = false
              goodValuePrice = selectSpuList[i].spuName
              break
            }
          }

          if (selectSpuList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请选择入库商品'
            })
          } else if (isHasEmptyValue) {
            this.$notify.error({
              title: '失败',
              message: `请核对${isHasEmpValue}入库商品数量及单品总价`
            })
          } else if (!goodNumFormatValid) {
            this.$notify({
              title: '提示',
              message: `${goodNumValue}出库数量请填写整数或保留3位小数`,
              type: 'warning'
            })
          } else if (!goodNumMaxValid) {
            this.$notify({
              title: '提示',
              message: `${goodNumvalueMax}出库数量不能大于可用库存`,
              type: 'warning'
            })
          } else if (!goodPriceValid) {
            this.$notify({
              title: '提示',
              dangerouslyUseHTMLString: true,
              message: `${goodValuePrice}出库单价核对格式<br>(整数或者两位小数)`,
              type: 'warning'
            })
          } else {
            this.dataForm.salesSendOrderGoodsDTOS = this.selectSpuList
            this.dataForm.sendOrderState = status
            let storeInfo = {}
            if (this.storeList && this.storeList.length > 0) {
              for (let i = 0; i < this.storeList.length; i++) {
                if (this.storeList[i].id === this.dataForm.storeId) {
                  storeInfo = this.storeList[i]
                  break
                }
              }
            }
            if (storeInfo) {
              this.dataForm.storeName = storeInfo.storeName
              this.dataForm.storeId = storeInfo.id
              this.dataForm.storeContract = storeInfo.contactName
              this.dataForm.storeContractPhone = storeInfo.contactPhone
            }
            this.dataForm.total = this.selSpuListTotal
            this.dataForm.totalPrice = this.selSpuListTotalPrice
            create(this.dataForm)
              .then(response => {
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    handleUpdate(row) {
      this.listWareHousesByPara()
      this.listStoresByPara()
      this.listSpuQuery.saleSendOrderId = row.id
      this.listSpuQuery.warehouseId = row.warehouseId
      this.listWarehouseGoods()
      this.dataForm = Object.assign({}, row)
      this.dataForm.sendOrderConpon = this.dataForm.sendOrderConpon ? this.dataForm.sendOrderConpon / 100 : 0
      this.dataForm.storeId = row.storeId
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.goodNumFormatValid = true
      this.goodNumMaxValid = true
      this.goodPriceValid = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAudit(row) {
      this.auditDialogVisible = true
      this.auditDataForm = {
        auditComment: '',
        sendOrderState: '1',
        salesSendOrderId: row.id,
        storePurchaseOrderId: row.storePurchaseOrderId,
        storeStockEntryId: row.storeStockEntryId
      }
    },
    auditOrderAndEntryStore() {
      if (this.auditDataForm.sendOrderState === '2') {
        if (this.auditDataForm.auditComment === '' || this.auditDataForm.auditComment.trim() === '') {
          this.$notify.error({
            title: '失败',
            message: '请填写驳回意见'
          })
          return
        }
      }
      this.auditFormLoading = true
      auditAndStoreEntry(this.auditDataForm)
        .then(response => {
          this.auditFormLoading = false
          this.auditDialogVisible = false
          this.$notify.success({
            title: '成功',
            message: '审核成功'
          })
          this.getList()
        })
        .catch(response => {
          this.auditFormLoading = false
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    auditOrder() {
      if (this.auditDataForm.sendOrderState === '2') {
        if (this.auditDataForm.auditComment === '' || this.auditDataForm.auditComment.trim() === '') {
          this.$notify.error({
            title: '失败',
            message: '请填写驳回意见'
          })
          return
        }
      }
      this.auditFormLoading = true
      audit(this.auditDataForm)
        .then(response => {
          this.auditFormLoading = false
          this.auditDialogVisible = false
          this.$notify.success({
            title: '成功',
            message: '审核成功'
          })
          this.getList()
        })
        .catch(response => {
          this.auditFormLoading = false
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    updateData(status) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          let isHasEmpValue = ''
          let goodNumFormatValid = true
          let goodNumValue = ''
          let goodNumMaxValid = true
          let goodNumvalueMax = ''
          let goodPriceValid = true
          let goodValuePrice = ''
          for (let i = 0; i < selectSpuList.length; i++) {
            // .sendGoodsPrice
            if (!selectSpuList[i].sendGoodsStock || !selectSpuList[i].sendGoodsAllPrice) {
              isHasEmptyValue = true
              isHasEmpValue = selectSpuList[i].spuName
              break
            }
            if (!goodsNumLimit(selectSpuList[i].sendGoodsStock)) {
              goodNumFormatValid = false
              goodNumValue = selectSpuList[i].spuName
              break
            }
            if (selectSpuList[i].sendGoodsStock && selectSpuList[i].warehouseSkuNum && selectSpuList[i].sendGoodsStock > selectSpuList[i].warehouseSkuNum) {
              goodNumMaxValid = false
              goodNumvalueMax = selectSpuList[i].spuName
              break
            }
            if (!goodsPriceLimit(selectSpuList[i].sendGoodsAllPrice)) {
              goodPriceValid = false
              goodValuePrice = selectSpuList[i].spuName
              break
            }
          }
          if (selectSpuList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请选择入库商品'
            })
          } else if (isHasEmptyValue) {
            this.$notify.error({
              title: '失败',
              message: `请核对${isHasEmpValue}入库商品数量及单价`
            })
          } else if (!goodNumFormatValid) {
            this.$notify({
              title: '提示',
              message: `${goodNumValue}出库数量请填写整数或保留3位小数`,
              type: 'warning'
            })
          } else if (!goodNumMaxValid) {
            this.$notify({
              title: '提示',
              message: `${goodNumvalueMax}出库数量不能大于可用库存`,
              type: 'warning'
            })
          } else if (!goodPriceValid) {
            this.$notify({
              title: '提示',
              dangerouslyUseHTMLString: true,
              message: `${goodValuePrice}出库单价核对格式<br>(整数或者两位小数)`,
              type: 'warning'
            })
          } else {
            this.dataForm.salesSendOrderGoodsDTOS = this.selectSpuList
            this.dataForm.sendOrderState = status
            let storeInfo = {}
            if (this.storeList && this.storeList.length > 0) {
              for (let i = 0; i < this.storeList.length; i++) {
                if (this.storeList[i].id === this.dataForm.storeId) {
                  storeInfo = this.storeList[i]
                  break
                }
              }
            }
            if (storeInfo) {
              this.dataForm.storeName = storeInfo.storeName
              this.dataForm.storeContract = storeInfo.contactName
              this.dataForm.storeContractPhone = storeInfo.contactPhone
            }
            this.dataForm.total = this.selSpuListTotal
            this.dataForm.totalPrice = this.selSpuListTotalPrice
            update(this.dataForm)
              .then(response => {
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }).catch(() => {
        return false
      })
    },
    handleSpuAdd(warehouseId) {
      this.spuDialogFormVisible = true
      this.listSpuQuery.warehouseId = warehouseId
      this.categoryOptions = []
      this.categorySecondLevelTree()
      this.refreshCategoryOptions()
      this.listGoods()
    },
    listWarehouseGoods() {
      this.listSpuQuery.status = 1
      listWarehouseSkusByPara(this.listSpuQuery)
        .then(response => {
          this.selectSpuList = response.data.data
        })
        .catch(() => {
          this.selectSpuList = []
        })
    },
    listGoods() {
      this.listSpuQuery.status = 1
      this.listSpuLoading = true
      querySkusByWarehouseId(this.listSpuQuery)
        .then(response => {
          this.spuList = response.data.data.items
          this.spuListTotal = response.data.data.total
          this.listSpuLoading = false
        })
        .catch(() => {
          this.spuList = []
          this.listSpuLoading = false
        })
    },
    ifCanSelSpu() {
      this.dataForm.warehouseIsSelected = true
      if (this.dataForm.warehouseId) {
        this.dataForm.warehouseIsSelected = false
      }
    },
    saveWarehouseSpu() {
      const selection = this.selectGoodList
      console.log(selection, '哈哈哈', this.selectSpuList)
      for (let i = 0; i < this.selectSpuList.length; i++) {
        for (let j = 0; j < selection.length; j++) {
          if (this.selectSpuList[i].skuId && this.selectSpuList[i].skuId === selection[j].skuId && (this.selectSpuList[i].sendGoodsStock || this.selectSpuList[i].sendGoodsPrice)) {
            this.$set(selection[j], 'sendGoodsStock', this.selectSpuList[i].sendGoodsStock)
            this.$set(selection[j], 'sendGoodsPrice', this.selectSpuList[i].sendGoodsPrice)
            break
          }
        }
      }
      const selNewArr = this.unique(selection.concat(this.selectSpuList))
      this.spuDialogFormVisible = false
      // this.selectSpuList = selection
      this.selectSpuList = selNewArr
    },
    unique(arr1) {
      const res = new Map()
      return arr1.filter((a) => !res.has(a.skuId) && res.set(a.skuId, 1))
    },
    removeSpu(skuId) {
      if (this.$refs.spuTable) {
        this.$refs.spuTable.clearSelection()
      }
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (this.selectSpuList[i].skuId === skuId) {
          this.selectSpuList.splice(i, 1)
          break
        }
      }
      if (this.selectSpuList) {
        this.selectSpuList.forEach(row => {
          if (this.$refs.spuTable) {
            this.$refs.spuTable.toggleRowSelection(row)
          }
        })
      }
    },
    categorySecondLevelTree() {
      categorySecondLevelTree()
        .then(response => {
          this.categoryList = response.data.data
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    handleCategoryOption(e) {
      if (e !== undefined) {
        const tag = e[e.length - 1]
        this.listSpuQuery.skuIds = tag // 回调指定分类
      } else {
        this.listSpuQuery.skuIds = undefined
      }
    },
    refreshCategoryOptions() {
      if (this.categoryOptions.length === 0) {
        categoryTree().then(response => {
          this.categoryOptions = response.data.data.map(item => {
            item.children.length == 0 ? delete item.children : ''
            return item
          })
        })
      }
    },
    changeSendOrderState() {
      const comment = this.auditDataForm.auditComment
      this.auditDataForm.auditComment = this.auditDataForm.sendOrderState === '1' ? '' : comment
    },
    handleDetail(row) {
      this.$router.push({ path: '/warehouse/send_order_detail?sOrderId=' + row.id })
    },
    handlePrint(row) {
      // var url = window.location.href.split('#')[0]
      // window.open(`${url}#/printdetail?pOrderId=${row.id}&outbound=2`)
      this.dialogTableVisible = true
      this.pOrderId = row.id
    },
    getRowKey(row) {
      return row.skuId
    },
    ifCanSelectSpu(row, index) {
      return row.warehouseSkuNum > 0
    },
    selectChange(selection) {
      this.selectGoodList = selection
    },
    goodsBuyNumLimit(row) {
      const flag = goodsNumLimit(row.sendGoodsStock)
      if (!flag) {
        // this.$notify({
        //   title: '提示',
        //   message: '出库数量请填写整数或保留3位小数',
        //   type: 'warning'
        // })
        this.goodNumFormatValid = false
        this.goodNumMaxValid = true
      } else {
        this.goodNumFormatValid = true
        if (row.sendGoodsStock && row.sendGoodsStock > row.warehouseSkuNum) {
          // this.$notify({
          //   title: '提示',
          //   message: '出库数量不能大于可用库存',
          //   type: 'warning'
          // })
          return false
        } else {
          return true
        }
      }
    },
    goodsPriceLimit(row) {
      const flag = goodsPriceLimit(row.sendGoodsPrice)
      if (!flag) {
        // this.$notify({
        //   title: '提示',
        //   dangerouslyUseHTMLString: true,
        //   message: '请出库单价核对格式<br>(整数或者两位小数)',
        //   type: 'warning'
        // })
        return false
      } else {
        return true
      }
    },
    skuSummary() {
      let startTime = ''
      let endTime = ''
      if (!this.listQuery.startTime || !this.listQuery.startTime) {
        this.$notify.info({
          title: '系统提示',
          message: '请选择导出时间范围'
        })
        return
      }
      if (this.listQuery.startTime && this.listQuery.startTime !== '') {
        var startTimeLong = this.listQuery.startTime
        startTime = timestampToTime(startTimeLong)
      }
      if (this.listQuery.endTime && this.listQuery.endTime !== '') {
        var endTimeLong = this.listQuery.endTime
        endTime = timestampToTime(endTimeLong)
      }
      exportSkuSummary(startTime, endTime, this.listQuery.storeId, this.listQuery.sendOrderState, extraStatusMap[this.listQuery.sendOrderState], this.listQuery.sendOrderNo, 12, this.listQuery.skuSearch)
    },
    checkFile() {
      document.querySelector('#fileinput').click()
    },
    checkFileSure(val) {
      const file = document.querySelector('#fileinput').files[0]
      this.file = file
      this.fileName = file.name
    },
    handleImport() {
      this.importDialogVisible = true
      // this.importOptLoading = false
      this.$set(this, 'fileName', '')
    },
    closeImportExcel() {
      this.importDialogVisible = false
      this.getList()
      this.resultList = []
    },
    salesSendImportExcel() {
      this.importOptLoading = true
      importExcel(this.file)
        .then(response => {
          debugger
          console.log('then ---' + response.data.data.result + '---  then')
          this.resultList = response.data.data.result
          this.importOptLoading = false
        })
        .catch(response => {
          response.data
          this.$notify.info({
            title: '提示',
            message: response.data.msg
          })
          this.importOptLoading = false
        })
      this.importOptLoading = false
    }
  }
}
</script>
